from fastapi import APIRouter, Depends, HTTPException
from app.services.oauth_service import handle_oauth_callback
from app.utils.mysql_helper import MySQLHelper

router = APIRouter(prefix="/shopify", tags=["Shopify OAuth"])

# 1. Shopify OAuth回调接口（GET请求，自动解析参数）
@router.get("/oauth/callback")
def oauth_callback(
    # FastAPI自动解析GET查询参数，无需手动处理
    shop: str,  # 对应URL ?shop=xxx.myshopify.com
    code: str,  # 对应URL ?code=授权临时码
    scope: str, # 对应URL ?scope=授权范围
    conn = Depends(MySQLHelper()._get_connection(auto_commit=True))  # 依赖注入MySQL连接
):
    try:
        # 路由层仅转发：参数→服务层→返回结果
        return handle_oauth_callback(conn, shop_domain=shop, code=code, scope=scope)
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"回调处理失败：{str(e)}")